package cn.huiyunche.driver.service.impl;

import cn.huiyunche.base.service.framework.utils.HYCUtils;
import cn.huiyunche.base.service.mappers.DVcstyleLicenseMapper;
import cn.huiyunche.base.service.mappers.ext.DVcstyleLicenseExtMapper;
import cn.huiyunche.base.service.model.DVcstyleLicense;
import cn.huiyunche.base.service.model.DVcstyleLicenseExample;
import cn.huiyunche.base.service.vo.DVcstyleLicenseVo;
import cn.huiyunche.base.service.vo.PageVo;
import cn.huiyunche.driver.service.DVcstyleLicenseService;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jxy on 16/12/14.
 */
@Service
public class DriverDVcstyleLicenseServiceImpl implements DVcstyleLicenseService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DriverDVcstyleLicenseServiceImpl.class);

    @Autowired
    private DVcstyleLicenseMapper dVcstyleLicenseMapper;

    @Autowired
    private DVcstyleLicenseExtMapper dVcstyleLicenseExtMapper;

    /**
     * redis 连接对象
     */
    private static Jedis jedis = null;

    /**
     * 准驾车型列表
     */
    private static final String ZL_RS_DVCSTYLELICENSE_LIST = "ZL_RS_DVCSTYLELICENSE_LIST";

    public DVcstyleLicense getVcStyleByStyleCode(String vcCode){
        LOGGER.info("getVcStyleByStyleCode params vcCode: {}",vcCode);
        DVcstyleLicenseExample dVcstyleLicenseExample = new DVcstyleLicenseExample();
        dVcstyleLicenseExample.createCriteria().andVcstylecodeEqualTo(vcCode);
        List<DVcstyleLicense> searchDVcstyleLicenseList = dVcstyleLicenseMapper.selectByExample(dVcstyleLicenseExample);

        if( CollectionUtils.isNotEmpty(searchDVcstyleLicenseList) ){
            return searchDVcstyleLicenseList.get(0);
        }
        return null;
    }

    public void addDvcStyleLicense(DVcstyleLicense dVcstyleLicense) {
        LOGGER.info("addDvcStyleLicense params dVcstyleLicense: {}", dVcstyleLicense);
        jedis = HYCUtils.getJedis();
        try {
            boolean validStyleCodeExist = validStyleCodeExist(dVcstyleLicense.getVcstylecode());
            if (validStyleCodeExist) {
                throw new BusinessException("车型编号已经存在");
            }
            dVcstyleLicense.setCreateTime(new Date());
            dVcstyleLicense.setUpdateTime(new Date());
            int res = dVcstyleLicenseMapper.insertSelective(dVcstyleLicense);
            if (res != 1) {
                throw new BusinessException("数据插入准驾车型表失败");
            }
            // 添加到redis
            jedis.lpush(ZL_RS_DVCSTYLELICENSE_LIST, JSONObject.toJSONString(dVcstyleLicense));
        } finally {
            jedis.close();
        }
    }

    public boolean validStyleCodeExist(String styleCode) {
        DVcstyleLicenseExample dVcstyleLicenseExample = new DVcstyleLicenseExample();
        dVcstyleLicenseExample.createCriteria().andVcstylecodeEqualTo(styleCode);
        List<DVcstyleLicense> dVcstyleLicenseList = dVcstyleLicenseMapper.selectByExample(dVcstyleLicenseExample);
        return dVcstyleLicenseList.size() > 0;
    }

    public void modifyDvcStyleLicense(DVcstyleLicense dVcstyleLicense) {
        LOGGER.info("modifyDvcStyleLicense params dVcstyleLicense: {}", dVcstyleLicense);
        jedis = HYCUtils.getJedis();
        try {
            DVcstyleLicense dvcstyle = dVcstyleLicenseMapper.selectByPrimaryKey(dVcstyleLicense.getId());
            if (dvcstyle == null) {
                throw new BusinessException("id对应的数据不存在");
            }
            if (!dvcstyle.getVcstylecode().equals(dVcstyleLicense.getVcstylecode())) {
                boolean validStyleCodeExist = validStyleCodeExist(dVcstyleLicense.getVcstylecode());
                if (validStyleCodeExist) {
                    throw new BusinessException("车型编号已经存在");
                }
            }
            dVcstyleLicense.setUpdateTime(new Date());
            int res = dVcstyleLicenseMapper.updateByPrimaryKeySelective(dVcstyleLicense);
            if (res != 1) {
                throw new BusinessException("修改准驾车型表失败");
            }
            // 根据key获得所有的数据
            List<String> data = jedis.lrange(ZL_RS_DVCSTYLELICENSE_LIST, 0, -1);
            if (null != data && data.size() > 0) {
                for (String s : data) {
                    // 判断是否包含这条数据
                    if (s.contains(dVcstyleLicense.getId() + "")) {
                        // 如果包含 则删除这条数据并将新数据插入
                        jedis.lrem(ZL_RS_DVCSTYLELICENSE_LIST, 1L, s);
                        break;
                    }
                }
                // 添加新数据到redis
                jedis.lpush(ZL_RS_DVCSTYLELICENSE_LIST, JSONObject.toJSONString(dVcstyleLicense));
            }
        } finally {
            jedis.close();
        }
    }

    public void deleteDvcStyleLicense(String id) {
        LOGGER.info("deleteDvcStyleLicense params id: {}", id);
        jedis = HYCUtils.getJedis();
        try {
            DVcstyleLicense dvcstyle = dVcstyleLicenseMapper.selectByPrimaryKey(Long.parseLong(id));
            if (dvcstyle == null) {
                throw new BusinessException("id对应的数据不存在");
            }
            int res = dVcstyleLicenseMapper.deleteByPrimaryKey(Long.parseLong(id));
            if (res != 1) {
                throw new BusinessException("删除准驾车型失败");
            }
            // 根据key获得所有的数据
            List<String> data = jedis.lrange(ZL_RS_DVCSTYLELICENSE_LIST, 0, -1);
            if (null != data && data.size() > 0) {
                for (String s : data) {
                    // 判断是否包含这条数据
                    if (s.contains(id)) {
                        // 如果包含 则删除这条数据
                        jedis.lrem(ZL_RS_DVCSTYLELICENSE_LIST, 1L, s);
                    }
                }
            }
        } finally {
            jedis.close();
        }

    }

    public Map<String, Object> getListByPage(PageVo page, DVcstyleLicenseVo dVcstyleLicenseVo) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> paramsMap = new HashMap<>();
        String orderByClause = StringUtils.isNotBlank(page.getOrder()) == true ? page.getOrder() : " id DESC";
        paramsMap.put("limitStart", page.getStartIndex());
        paramsMap.put("limitEnd", page.getPageSize());
        paramsMap.put("orderByClause", orderByClause);
        if (StringUtils.isNotBlank(dVcstyleLicenseVo.getVcstyletype())) {
            paramsMap.put("vcstyletype", dVcstyleLicenseVo.getVcstyletype());
        }

        page.setTotalRecord(dVcstyleLicenseExtMapper.countByCondations(paramsMap));
        List<DVcstyleLicense> styleLicenseList = dVcstyleLicenseExtMapper.getListByPage(paramsMap);

        map.put("page", page);
        map.put("styleLicenseList", styleLicenseList);
        return map;

    }

    public Map<String, Object> getListByPage(PageVo page) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> paramsMap = new HashMap<>();
        String orderByClause = StringUtils.isNotBlank(page.getOrder()) == true ? page.getOrder() : " id DESC";
        paramsMap.put("limitStart", page.getStartIndex());
        paramsMap.put("limitEnd", page.getPageSize());
        paramsMap.put("orderByClause", orderByClause);

        page.setTotalRecord(dVcstyleLicenseMapper.countByCondations(paramsMap));
        List<DVcstyleLicense> styleLicenseList = dVcstyleLicenseMapper.getListByPage(paramsMap);

        map.put("page", page);
        map.put("styleLicenseList", styleLicenseList);
        return map;

    }

}
